<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 

class Block_Admin_Page_Toolbar extends Core_Block {
	
	protected $_collection    = null;
	
	protected $_pageVarName    = 'p';
	
	protected $_limitVarName   = 'limit';

	public function setCollection($collection) {
		$this->_collection = $collection;
		// apply paging
		if ($this->getTotal() > 0) {
			$limit = $this->getCurrentLimit();
			$page = $this->getCurrentPage();
			$offset = ($page - 1) * $limit;
			$collection->getSelect()->limit($limit, $offset);
		}
	}
	
	public function getCollection() {
		return $this->_collection;
	}
	
	public function getTotal() {
		if ($this->getData('total')==null) {
			$select = clone $this->getCollection()->getSelect();
			$countSql = $this->getCountSql($select); 
			$query = App::db()->query($countSql);
			$row = $query->row_array();
			$this->setData('total', (int)$row['item_count']);
		}
		return $this->getData('total');
	}
	
	public function getCurrentLimit() {
		$cookie = App::objectSingleton('Core_Cookie');
		if ($this->getData('limit')==null) {
			if ($limit = App::get($this->_limitVarName)) {
				$cookie->set('limit', App::get($this->_limitVarName));
			} else {
				$limit = $cookie->get('limit') ? $cookie->get('limit') : $this->getDefaultLimit();
			}
			$this->setData('limit', (int)$limit);
		}
		return $this->getData('limit');
	}
	
	private function getCountSql(Core_Db_Select $sql) {
		$group = $sql->getPart(Core_Db_Select::GROUP);
		$select = clone $sql;
		$select->resetPart(Core_Db_Select::ORDER);
		if (empty($group)) {
			$select->setPart(Core_Db_Select::COLUMNS, array('COUNT(*) AS item_count'));
		} else {
			$select = 'SELECT COUNT(*) AS item_count FROM (' . $sql . ') AS count_table';
		}
		return $select;
	}
	
	public function getAvailableLimit() {
		return array(10, 30, 50, 100);
	}
	
	public function getDefaultLimit() {
		return 10;
	}
	
	public function isLimitCurrent($val) {
		return $val==$this->getCurrentLimit();
	}
	
	public function getLimitUrl($val) {
		$query = App::get();
		$query[$this->_limitVarName] = $val;
		return App::url('*/*/*', array('_query' => $query));
	}
	
	public function isPagingVisible() {
		return $this->getPageCount() > 1;
	}

	public function getCurrentPage() {
        $page = App::get($this->_pageVarName);
		if (empty($page)) {
			return 1;
		} elseif ($page > $this->getPageCount() || $page < 1) {
			App::redirect($this->getPageUrl(1));
		}
        return $page;
	}
	
	public function getPageCount() {
		if ($this->getData('page_count')==null) {
			$this->setData('page_count', ceil($this->getTotal() / $this->getLimit()));
		}
		return $this->getData('page_count');
	}

	public function isCurrentPage($page) {
		return $page == $this->getCurrentPage();
	}
	
	public function getPageUrl($page) {
		$page = max(1, min($page, $this->getPageCount()));
		$query = App::get();
		$query[$this->_pageVarName] = $page!=1 ? $page : null;
		return App::url('*/*/*', array('_query' => $query));
	}
	
}

